package com.eatme.web.app.coupon.template.schedule;

import com.eatme.web.app.coupon.common.vo.TemplateRule;
import com.eatme.web.app.coupon.template.dao.CouponTemplateDao;
import com.eatme.web.app.coupon.template.entity.CouponTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时清理已过期的优惠券模版
 */
@Component
public class CouponTemplateScheduleTask {

    private static final Logger LOG = LoggerFactory.getLogger(CouponTemplateScheduleTask.class);



    /** couponTemplateDao */
    private  final CouponTemplateDao couponTemplateDao;


    @Autowired
    public CouponTemplateScheduleTask(CouponTemplateDao couponTemplateDao) {
        this.couponTemplateDao = couponTemplateDao;
    }

    /**
     * 下线已过期的优惠券模版
     */
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void offlineCouponTemplate() {
        LOG.info("Start To Expire CouponTemplate");
        List<CouponTemplate> templates = couponTemplateDao.findAllByExpired(false);
        if (CollectionUtils.isEmpty(templates)) {
            LOG.info("Done To Expire CouponTemplate.");
            return;
        }
        Date cur = new Date();
        List<CouponTemplate> expiredTemplates = new ArrayList<>(templates.size());

        templates.forEach(t -> {
            //根据优惠券模版规则中的"过期规则"校验模版是否过期
            TemplateRule rule = t.getRule();
            if (rule.getExpiration().getDeadLine() < cur.getTime()) {
                t.setExpired(true);
                expiredTemplates.add(t);
            }
            if (CollectionUtils.isNotEmpty(expiredTemplates)) {
                LOG.info("Expired CouponTemplate Num: {}",
                        couponTemplateDao.saveAll(expiredTemplates));
            }
        });

    }
}
